package com.techbrand.lb7.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.web.bind.RequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;

import com.techbrand.lb7.dao.CustomerDao;
import com.techbrand.lb7.domain.Customer;

public class CustomerController extends MultiActionController {

	private CustomerDao customerDao;

	public ModelAndView handleViewAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("customerList", customerDao.getAll());
		return new ModelAndView("customer-viewAll", model);
	}
	
	public ModelAndView handleView(HttpServletRequest request, HttpServletResponse response) throws Exception {
		long custId = RequestUtils.getRequiredLongParameter(request, "custId");
		Customer customer = customerDao.getById(custId);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("customer", customer);
		return new ModelAndView("customer-view", model);
	}
	
	public ModelAndView handleDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		long custId = RequestUtils.getRequiredLongParameter(request, "custId");
		customerDao.deleteById(custId);
		return new ModelAndView(new RedirectView("viewAll.htm"));
	}
	
	public ModelAndView handleDeleteSelected(HttpServletRequest request, HttpServletResponse response) throws Exception {
		long[] custIdsParam = RequestUtils.getRequiredLongParameters(request, "custIds");
		List<Long> customerIds = Arrays.asList(ArrayUtils.toObject(custIdsParam));
		customerDao.deleteList(customerIds);
		return new ModelAndView(new RedirectView("viewAll.htm"));
	}
	
	public CustomerDao getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
}
